package rede.servidor;

import rede.Autenticacao;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import rede.Login;

/**
 * @author tiagosn
 */
public class RecebeConexao implements Runnable{
    Servidor servidor;
    
    public RecebeConexao(Servidor servidor){
        this.servidor = servidor;
    }

    public void run() {
        while(true){
            try {
                Socket socketCliente = servidor.getServerSocket().accept();
                ObjectOutputStream saida = new ObjectOutputStream(socketCliente.getOutputStream());
                ObjectInputStream entrada = new ObjectInputStream(socketCliente.getInputStream());
                try {
                    Login login = (Login)entrada.readObject();
                    servidor.autenticarCliente(login.getLogin(), socketCliente, entrada, saida);
                    saida.writeObject(new Autenticacao(true));

                    servidor.enviarListaUsuarios();
                    servidor.atualizarListaClientes();

                    Thread recebeMensagem = new Thread(new RecebeMensagem(servidor, login.getLogin(), entrada));
                    recebeMensagem.start();
                } catch (ClassNotFoundException ex) {
                    ex.printStackTrace();
                    entrada.close();
                    saida.close();
                    continue;
                }
            } catch (IOException ex) {
                //ex.printStackTrace();
                break; /// verificar esse break
            }
        }
    }
}
